<template>
  <div class="content">
    <van-field v-model="tel" clearable placeholder="请输入手机号码" />
    <van-button @click="docheckPhoneFn" :disabled="!flag" round block color="#ff6666" style="margin-top: 20px">下一步</van-button>
    <p class="note">
      <van-checkbox icon-size="16" v-model="checked" >同意*******协议</van-checkbox>
    </p>
  </div>
</template>
<script>
import Vue from 'vue'
import { Field, Button, Checkbox, Dialog } from 'vant'
import { docheckphone } from '@/api/user'
Vue.use(Field)
Vue.use(Button)
Vue.use(Checkbox)
Vue.use(Dialog)
export default {
  data () {
    return {
      tel: '',
      checked: false
    }
  },
  computed: {
    flag () {
      return /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/.test(this.tel)
    }
  },
  methods: {
    docheckPhoneFn () {
      if (!this.checked) {
        Dialog.confirm({
          message: '请先勾选用户协议',
          confirmButtonText: '同意并且继续',
          cancelButtonText: '取消'
        })
          .then(() => {
            this.checked = true
            docheckphone({ tel: this.tel }).then(res => {
              if (res.data.code === '10005') {
                Dialog.confirm({
                  message: '该手机号已被注册',
                  confirmButtonText: '直接登录',
                  cancelButtonText: '取消'
                }).then(() => {
                  this.$router.back() // 跳转到登录
                }).catch(() => {})
              } else {
                Dialog.confirm({
                  message: '我们将发送短信验证码至<br/>' + this.tel,
                  confirmButtonText: '确定',
                  cancelButtonText: '取消'
                }).then(() => {
                  localStorage.setItem('tel', this.tel)
                  this.$router.push('/register/step2')
                }).catch(() => {})
              }
            })
          })
          .catch(() => {
          })
      } else {
        docheckphone({ tel: this.tel }).then(res => {
          if (res.data.code === '10005') {
            Dialog.confirm({
              message: '该手机号已被注册',
              confirmButtonText: '直接登录',
              cancelButtonText: '取消'
            }).then(() => {
              this.$router.back() // 跳转到登录
            }).catch(() => {})
          } else {
            Dialog.confirm({
              message: '我们将发送短信验证码至<br/>' + this.tel,
              confirmButtonText: '确定',
              cancelButtonText: '取消'
            }).then(() => {
              localStorage.setItem('tel', this.tel)
              this.$router.push('/register/step2')
            }).catch(() => {})
          }
        })
      }
    }
  }
}

</script>

<style lang="stylus" scoped>
.note
  position fixed
  bottom 5px
  left 50%
  transform translateX(-50%)
  opacity 0.4
</style>
